package com.lemon.core.base.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
import lombok.Data;

/**
 * 统一响应实体
 *
 * @author pan
 * @since 2018-03-16
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {

    @ApiModelProperty(value = "响应码", required = true)
    private int code;

    @ApiModelProperty(value = "响应消息", required = true)
    private String msg;

    @ApiModelProperty(value = "响应数据")
    private T data;

    public static <T> Result<T> success() {
        return data(null);
    }

    public static <T> Result<T> data(T data) {
        ResultCode resultCode = ResultCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            resultCode = ResultCode.SYSTEM_EXECUTION_ERROR;
        }
        return result(resultCode, data);
    }

    public static <T> Result<PageInfo<T>> page(List<T> data, Long total) {
        return page(new PageInfo<>(data, total));
    }

    public static <T> Result<PageInfo<T>> page(PageInfo<T> pageInfo) {
        Result<PageInfo<T>> result = new Result<>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setMsg(ResultCode.SUCCESS.getMsg());
        result.setData(pageInfo);
        return result;
    }

    public static <T> Result<T> failed() {
        return result(ResultCode.SYSTEM_EXECUTION_ERROR, null);
    }

    public static <T> Result<T> failed(String msg) {
        return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), msg, null);
    }

    public static <T> Result<T> status(boolean status) {
        if (status) {
            return success();
        } else {
            return failed();
        }
    }

    public static <T> Result<T> failed(IResultCode resultCode) {
        return result(resultCode.getCode(), resultCode.getMsg(), null);
    }

    public static <T> Result<T> failed(IResultCode resultCode, String msg) {
        return result(resultCode.getCode(), msg, null);
    }

    private static <T> Result<T> result(IResultCode resultCode, T data) {
        return result(resultCode.getCode(), resultCode.getMsg(), data);
    }

    private static <T> Result<T> result(Integer code, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }

    public static boolean isSuccess(Result<?> result) {
        return result != null && ResultCode.SUCCESS.getCode() == result.getCode();
    }
}
